package com.csjbot.blackgaga;

import android.app.Application;
import android.content.Context;
import android.media.AudioManager;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.baidu.duersdk.DuerSDK;
import com.baidu.duersdk.DuerSDKFactory;
import com.baidu.duersdk.sdkconfig.SdkConfigInterface;
import com.baidu.duersdk.utils.FileUtil;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.csjbot.blackgaga.feature.navigation.NaviAction;
import com.csjbot.blackgaga.model.http.factory.RetrofitFactory;
import com.csjbot.blackgaga.model.http.factory.ServerFactory;
import com.csjbot.blackgaga.model.http.product.ProductProxy;
import com.csjbot.blackgaga.model.http.workstream.Logo;
import com.csjbot.blackgaga.network.ShellUtil;
import com.csjbot.blackgaga.push.BPush;
import com.csjbot.blackgaga.router.BRouter;
import com.csjbot.blackgaga.util.ConfInfoUtil;
import com.csjbot.blackgaga.util.SharedKey;
import com.csjbot.blackgaga.util.SharedPreUtil;
import com.csjbot.blackgaga.util.locationutil.LocationUtil;
import com.csjbot.coshandler.log.CsjlogProxy;
import com.csjbot.coshandler.log.Csjlogger;
import com.iflytek.cloud.SpeechUtility;
import com.tencent.bugly.crashreport.CrashReport;

import org.json.JSONObject;

import java.io.File;

/**
 * Created by xiasuhuei321 on 2017/8/14.
 * author:luo
 * e-mail:xiasuhuei321@163.com
 * <p>
 * desc:初始化的各种操作
 */

public class BaseApplication extends Application {

    static Application app;
    public static boolean isFirstComing = true;


    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        /* 初始化retrofit */
        RetrofitFactory.initClient();
        /* 第一次加载产品数据 */
//        firstGetData();
        /* 科大讯飞appid */
        SpeechUtility.createUtility(this, "appid=" + getString(R.string.app_id));
        /* 初始化度秘 */
        initDuer();
        /* 初始化推送 */
        BPush.init(this);
        BRouter.init(this, BuildConfig.DEBUG);

        setUncaughtExceptionHandler();
        initBaiduMap();
        ConfInfoUtil.init();


        CrashReport.initCrashReport(getApplicationContext(), "99de59fd2e", false);
        if (!TextUtils.isEmpty(ConfInfoUtil.getSN())) {
            Logo.getLogo(ConfInfoUtil.getSN());
        }

        setVoice();//关机后恢复之前设置的音量
        NaviAction.getInstance().initData();
    }

    private void setVoice() {
        AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int volume = SharedPreUtil.getInt(SharedKey.VOICENAME, SharedKey.VOICEKEY, 8);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
    }

    private void setUncaughtExceptionHandler() {
        Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
            // 输出异常！
            throwable.printStackTrace();
            CsjlogProxy.getInstance().error(throwable.toString());
            if (!BuildConfig.DEBUG) {
                Csjlogger.debug("-异常重启-");
                new Thread(() -> {
                    com.csjbot.blackgaga.model.tcp.factory.ServerFactory.getSpeakInstance().startSpeaking("程序异常,正在重启!", null);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ShellUtil.execCmd("am force-stop com.csjbot.blackgaga\nam start -n com.csjbot.blackgaga/com.csjbot.blackgaga.MainActivity", true, false);

                }).start();
            }
        });

    }

    /**
     * 第一次加载产品数据
     */
    private void firstGetData() {
        ProductProxy proxy = ServerFactory.createProduct();
        proxy.getRobotMenuList(true);
    }

    public static Application getAppContext() {
        return app;
    }

    /**
     * 初始化度秘
     */
    private void initDuer() {
        DuerSDK duerSDK = DuerSDKFactory.getDuerSDK();

        //测试appid,appkey
        String appid = "dmD0DFAE6C3C8F9A89";
        String appkey = "4A1EB4F1C9160C02FD23D2C65C0A9BF5";

        //统计测试，sd卡配置文件动态设置appid,appkey
        File sdkConfigFile = new File(SdkConfigInterface.APP_CONFIGFILE);
        if (sdkConfigFile.isFile() && sdkConfigFile.exists()) {
            try {
                String content = FileUtil.getFileOutputString(SdkConfigInterface.APP_CONFIGFILE);
                JSONObject contentJson = new JSONObject(content);
                String fileAppId = contentJson.optString("appid");
                String fileAppKey = contentJson.optString("appkey");
                if (!TextUtils.isEmpty(fileAppId) && !TextUtils.isEmpty(fileAppKey)) {
                    appid = fileAppId;
                    appkey = fileAppKey;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //初始化sdk
        duerSDK.addSDKErrorLisener(new DuerSDK.SDKErrorLisner() {
            @Override
            public void onError(int i) {
            }
        });
        duerSDK.initSDK(this, appid, appkey);

        BRouter.init(this, BuildConfig.DEBUG);
    }

    /**
     * 初始化百度地图和定位
     */
    private void initBaiduMap() {
        // 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
        SDKInitializer.initialize(this);
        //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
        //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
        SDKInitializer.setCoordType(CoordType.BD09LL);
        LocationUtil.init(this);
        LocationUtil.start();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
